﻿using System;
using System.Collections.Generic;
using System.Text;

namespace IllustratedCsharp7_ch9
{
    class chapt9_14UserDefinedTypeConversion
    {
        static void _Main()
        {
            LimitedInt li = 500;                                    //将500转换为LimitedInt
            int value = li;                                         //将LimitedInt转换为int
            Console.WriteLine($"li:{ li.TheValue },value:{ value }");


            LimitedInt1 li1 = (LimitedInt1)500;
            int value1 = (int)li1;
            Console.WriteLine($"li1:{ li1.TheValue },value:{ value1 }");
        }
    }
    //用户自定义类型转换-隐式转换
    class LimitedInt
    {
        const int MaxValue = 100;
        const int MinValue = 0;

        public static implicit operator int(LimitedInt li) //类型转换，将LimitedInt转换为int
        {
            return li.TheValue;
        }
        public static implicit operator LimitedInt(int x)  //类型转换，将int转换为LimitedInt
        {
            LimitedInt li = new LimitedInt();
            li.TheValue = x;
            return li;
        }

        private int mTheValue = 0;
        public int TheValue
        {
            get { return mTheValue; }
            set {
                if (value < MinValue)
                    mTheValue = 0;
                else
                    mTheValue = value > MaxValue
                                ? MaxValue
                                : value;
            }
        }
    }

    //用户自定义类型转换-显式转换
    class LimitedInt1
    {
        const int MaxValue = 100;
        const int MinValue = 0;

        public static explicit operator int(LimitedInt1 li) //类型转换，将LimitedInt转换为int
        {
            return li.TheValue;
        }
        public static explicit operator LimitedInt1(int x)  //类型转换，将int转换为LimitedInt
        {
            LimitedInt1 li = new LimitedInt1();
            li.TheValue = x;
            return li;
        }

        private int mTheValue = 0;
        public int TheValue
        {
            get { return mTheValue; }
            set
            {
                if (value < MinValue)
                    mTheValue = 0;
                else
                    mTheValue = value > MaxValue
                                ? MaxValue
                                : value;
            }
        }
    }
}
